package com.example.clocktest

import android.annotation.SuppressLint
import android.app.AppOpsManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat.getSystemService

class AlarmReceiver : BroadcastReceiver() {

    private lateinit var vibrator: Vibrator

    override fun onReceive(context: Context, intent: Intent) {
        // 检查是否已初始化
        if (!::vibrator.isInitialized) {
            vibrator = context.getSystemService(/* name = */ Context.VIBRATOR_SERVICE) as Vibrator
        }

        val state = intent.getIntExtra("state", 0)
        if (state == 1) {
            showNotification(context, "提醒：时间到了！")
        }else{
            cancel(context, "提醒：时间到了！")
        }
    }
    private fun cancel(context: Context, message: String) {
        vibrator.cancel()
    }
    private fun showNotification(context: Context, message: String) {

        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channelId = "reminder_channel"
        val channelName = "Reminder Channel"

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        val notification = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("提醒")
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .build()

        notificationManager.notify(1, notification)

        vibrate(context)
    }

    @SuppressLint("ServiceCast")
    private fun vibrate(context: Context) {
        // 检查设备是否支持振动
        if (vibrator.hasVibrator()) {
            // 设置振动模式
            // 参数：振动时长（毫秒），暂停时长（毫秒），重复次数（-1 表示不重复）
            val vibrationPattern = longArrayOf(0, 500, 300, 500) // 0 表示立即开始振动
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                vibrator.vibrate(VibrationEffect.createWaveform(vibrationPattern, 1))
            }
        }
    }
}